<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出入账" prop="transactionType">
        <el-select v-model="queryParams.transactionType" placeholder="请选择出入账" clearable>
          <el-option
            v-for="dict in dict.type.admin_transaction_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易对象" prop="counterpartyType">
        <el-select v-model="queryParams.counterpartyType" placeholder="请选择交易对象" clearable>
          <el-option
            v-for="dict in dict.type.admin_counterparty_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总金额" class="total-amount-range">
        <el-input
          v-model="queryParams.totalAmountMin"
          placeholder="最小金额"
          clearable
          style="width: 120px; margin-right: 5px;"
          @keyup.enter.native="handleQuery"
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.totalAmountMax"
          placeholder="最大金额"
          clearable
          style="width: 120px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" class="created-time-range">
        <el-date-picker clearable
          v-model="queryParams.createdAtMin"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="开始时间"
          style="width: 160px; margin-right: 5px;">
        </el-date-picker>
        <span style="margin: 0 5px;">-</span>
        <el-date-picker clearable
          v-model="queryParams.createdAtMax"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="结束时间"
          style="width: 160px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否启用" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.admin_is_active"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['accounting:accounting:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['accounting:accounting:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['accounting:accounting:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['accounting:accounting:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="出入账" align="center" prop="transactionType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_transaction_type" :value="scope.row.transactionType"/>
        </template>
      </el-table-column>
      <el-table-column label="交易对象" align="center" prop="counterpartyType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_counterparty_type" :value="scope.row.counterpartyType"/>
        </template>
      </el-table-column>
      <el-table-column label="交易分类" align="center" prop="category" />
      <el-table-column label="数量" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.quantity && scope.row.unitOfMeasure" style="display: inline-block;">
            {{ scope.row.quantity }}&nbsp;<dict-tag style="display: inline;" :options="dict.type.admin_unit_of_measure" :value="scope.row.unitOfMeasure"/>
          </span>
          <span v-else-if="scope.row.quantity">{{ scope.row.quantity }}</span>
          <span v-else-if="scope.row.unitOfMeasure">
            <dict-tag style="display: inline;" :options="dict.type.admin_unit_of_measure" :value="scope.row.unitOfMeasure"/>
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="单价（元）" align="center" prop="unitPrice">
        <template slot-scope="scope">
          <span>{{ scope.row.unitPrice ? scope.row.unitPrice + ' 元' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额（元）" align="center" prop="totalAmount">
        <template slot-scope="scope">
          <span v-if="scope.row.totalAmount">
            {{ scope.row.totalAmount }} 元
            <span v-if="scope.row.quantity && scope.row.unitPrice && (scope.row.quantity * scope.row.unitPrice).toFixed(2) !== scope.row.totalAmount.toFixed(2)" style="color: red;">(错误)</span>
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="isActive">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_is_active" :value="scope.row.isActive"/>
        </template>
      </el-table-column>
      <el-table-column label="票据/证明" align="center" prop="invoiceUrl" width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.invoiceUrl">
            <image-preview
              v-for="(img, index) in scope.row.invoiceUrl.split(',')"
              :key="index"
              :src="img"
              :width="50"
              :height="50"
              style="margin-right: 5px;"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['accounting:accounting:edit']"
          >修改</el-button>

        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改后台-记账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出入账" prop="transactionType">
          <el-select v-model="form.transactionType" placeholder="请选择出入账">
            <el-option
              v-for="dict in dict.type.admin_transaction_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易对象" prop="counterpartyType">
          <el-select v-model="form.counterpartyType" placeholder="请选择交易对象">
            <el-option
              v-for="dict in dict.type.admin_counterparty_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入交易分类" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="总数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入总数量" />
        </el-form-item>
        <el-form-item label="表示计量单位" prop="unitOfMeasure">
          <el-select v-model="form.unitOfMeasure" placeholder="请选择表示计量单位">
            <el-option
              v-for="dict in dict.type.admin_unit_of_measure"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否启用">
            <el-option
              v-for="dict in dict.type.admin_is_active"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="票据/证明" prop="invoiceUrl">
          <image-upload v-model="form.invoiceUrl" multiple/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAccounting, getAccounting, delAccounting, addAccounting, updateAccounting } from "@/api/accounting/accounting"

export default {
  name: "Accounting",
  dicts: ['admin_unit_of_measure', 'admin_is_active', 'admin_transaction_type', 'admin_counterparty_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 后台-记账表格数据
      accountingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transactionType: null,
        counterpartyType: null,
        totalAmountMin: null,
        totalAmountMax: null,
        createdAtMin: null,
        createdAtMax: null,
        isActive: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        transactionType: [
          { required: true, message: "出入账不能为空", trigger: "change" }
        ],
        counterpartyType: [
          { required: true, message: "交易对象不能为空", trigger: "change" }
        ],
        category: [
          { required: true, message: "交易分类不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "总数量不能为空", trigger: "blur" }
        ],
        unitOfMeasure: [
          { required: true, message: "表示计量单位不能为空", trigger: "change" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询后台-记账列表 */
    getList() {
      this.loading = true
      listAccounting(this.queryParams).then(response => {
        this.accountingList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        transactionType: null,
        counterpartyType: null,
        category: null,
        totalAmount: null,
        quantity: null,
        unitOfMeasure: null,
        unitPrice: null,
        createdAt: null,
        createdBy: null,
        updatedAt: null,
        updatedBy: null,
        isActive: null,
        invoiceUrl: null,
        remark: null,
        isDeleted: null,
        deletedAt: null,
        tenantId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加后台-记账"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAccounting(id).then(response => {
        // 处理逗号分隔的发票URL，转换为数组以便上传组件正确显示
        if (response.data.invoiceUrl && typeof response.data.invoiceUrl === 'string') {
          response.data.invoiceUrl = response.data.invoiceUrl.split(',')
        }
        this.form = response.data
        this.open = true
        this.title = "修改后台-记账"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理多张发票，将数组转换为逗号分隔的字符串
          if (Array.isArray(this.form.invoiceUrl)) {
            this.form.invoiceUrl = this.form.invoiceUrl.join(',')
          }
          
          if (this.form.id != null) {
            updateAccounting(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAccounting(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除后台-记账编号为"' + ids + '"的数据项？').then(function() {
        return delAccounting(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/accounting/export', {
        ...this.queryParams
      }, `accounting_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
